<template>
  <el-dialog
    :model-value="visible"
    title="创建账户"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="手机号" prop="phone">
        <el-select 
          v-model="form.phone" 
          placeholder="请选择手机号" 
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="phone in phoneNumbers"
            :key="phone.phone"
            :label="getPhoneLabel(phone)"
            :value="phone.phone"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="预存费用" prop="preDeposit">
        <el-input 
          v-model.number="form.preDeposit" 
          placeholder="请输入预存费用" 
          type="number"
        />
      </el-form-item>
      
      <el-form-item label="总消费" prop="totalConsumption">
        <el-input 
          v-model.number="form.totalConsumption" 
          placeholder="请输入总消费" 
          type="number"
        />
      </el-form-item>
      
      <el-form-item label="月消费" prop="monthConsumption">
        <el-input 
          v-model.number="form.monthConsumption" 
          placeholder="请输入月消费" 
          type="number"
        />
      </el-form-item>
      
      <el-form-item label="是否欠费" prop="isArrears">
        <el-select v-model="form.isArrears" placeholder="请选择是否欠费" style="width: 100%">
          <el-option label="是" :value="1" />
          <el-option label="否" :value="0" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="欠费金额" prop="arrearsAmount">
        <el-input 
          v-model.number="form.arrearsAmount" 
          placeholder="请输入欠费金额" 
          type="number"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确认创建
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { createAccountInfo, getAccountInfo } from '@/apis/account'
import { getPhoneNumberInfo } from '@/apis/phoneNumber'

export default {
  name: 'CreateAccount',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const submitLoading = ref(false)
    const phoneNumbers = ref([])
    
    const form = reactive({
      phone: '',
      preDeposit: 0,
      totalConsumption: 0,
      monthConsumption: 0,
      isArrears: 0,
      arrearsAmount: 0
    })
    
    // 自定义验证规则：检查手机号是否已被使用
    const validatePhoneUnique = async (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择手机号'));
        return;
      }
      
      try {
        // 获取所有账户信息
        const res = await getAccountInfo();
        if (res && res.code === 0 && res.data && res.data.records) {
          const existingAccount = res.data.records.find(account => account.phone === value);
          if (existingAccount) {
            callback(new Error('该手机号已被其他账户使用'));
            return;
          }
        }
        callback();
      } catch (error) {
        console.error('验证手机号唯一性失败:', error);
        // 即使验证失败也允许继续，避免网络问题阻断操作
        callback();
      }
    };
    
    const rules = {
      phone: [
        { required: true, message: '请选择手机号', trigger: 'change' },
        { validator: validatePhoneUnique, trigger: 'change' }
      ],
      preDeposit: [
        { required: true, message: '请输入预存费用', trigger: 'blur' }
      ],
      totalConsumption: [
        { required: true, message: '请输入总消费', trigger: 'blur' }
      ],
      monthConsumption: [
        { required: true, message: '请输入月消费', trigger: 'blur' }
      ],
      isArrears: [
        { required: true, message: '请选择是否欠费', trigger: 'change' }
      ],
      arrearsAmount: [
        { required: true, message: '请输入欠费金额', trigger: 'blur' }
      ]
    }
    
    // 获取手机号标签显示文本
    const getPhoneLabel = (phone) => {
      const phoneText = phone.phone || '';
      const customerText = phone.customerName || phone.name || phone.customer || '';
      if (customerText) {
        return `${phoneText} (${customerText})`;
      }
      return phoneText;
    };

    // 获取手机号列表
    const fetchPhoneNumbers = async () => {
      try {
        const res = await getPhoneNumberInfo();
        if (res && res.code === 0) {
          phoneNumbers.value = Array.isArray(res.data) ? res.data : [];
        }
      } catch (error) {
        console.error('获取手机号列表失败:', error);
        ElMessage.error('获取手机号列表失败');
        phoneNumbers.value = [];
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (['preDeposit', 'totalConsumption', 'monthConsumption', 'arrearsAmount'].includes(key)) {
          form[key] = 0;
        } else if (key === 'isArrears') {
          form[key] = 0;
        } else {
          form[key] = '';
        }
      });
    }
    
    // 关闭弹窗
    const handleClose = () => {
      resetForm();
      emit('update:visible', false);
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await formRef.value.validate();
        submitLoading.value = true;
        
        // 再次检查手机号是否已被使用（防止在填写表单期间被其他用户占用）
        const checkRes = await getAccountInfo();
        if (checkRes && checkRes.code === 0 && checkRes.data && checkRes.data.records) {
          const existingAccount = checkRes.data.records.find(account => account.phone === form.phone);
          if (existingAccount) {
            ElMessage.error('该手机号已被其他账户使用，请选择其他手机号');
            submitLoading.value = false;
            return;
          }
        }
        
        // 准备请求数据
        const requestData = {
          phone: form.phone,
          preDeposit: parseFloat(form.preDeposit) || 0,
          totalConsumption: parseFloat(form.totalConsumption) || 0,
          monthConsumption: parseFloat(form.monthConsumption) || 0,
          isArrears: parseInt(form.isArrears),
          arrearsAmount: parseFloat(form.arrearsAmount) || 0
        };
        
        const res = await createAccountInfo(requestData);
        if (res && res.code === 0) {
          ElMessage.success('账户创建成功');
          resetForm();
          emit('success');
          handleClose();
        } else {
          ElMessage.error(res?.msg || '创建失败');
        }
      } catch (error) {
        console.error('创建账户失败:', error);
        ElMessage.error('创建账户失败');
      } finally {
        submitLoading.value = false;
      }
    };
    
    // 初始化获取手机号列表
    onMounted(() => {
      fetchPhoneNumbers();
    });
    
    return {
      formRef,
      form,
      rules,
      submitLoading,
      phoneNumbers,
      getPhoneLabel,
      resetForm,
      handleClose,
      handleSubmit
    };
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>